package com.atguigu.gulimall.product.bn.controller;

import com.atguigu.gulimall.product.bn.bean.DataToken;
import com.atguigu.gulimall.product.bn.myuntil.UrlMap;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @NAME: BnController
 * @USER: wjj
 * @DATE: 2023/8/1
 * @TIME: 10:16
 * @DAY_NAME_FULL: 星期二
 * @PROJECT_NAME: boot-01-helloworld
 */
@Controller
public class BnController {
    private boolean fid = false;//判断是否是消息菜单
    private String encrypt;
    private String jieMiBody;
    private String post2;
    private String s1;//截取字符串中的解密内容，匹配规则
    private String s2;//截取字符串中的消息id，匹配规则
    private String s3;//截取字符串中的消息类型，匹配规则
    private String s4;//截取字符串中的消息文件的fid，匹配规则
    private String type_text;//消息内容
    private String mid;//消息id
    private boolean message_id;//消息id是否存在
    private boolean message_fid;//文件id是否存在
    private String event_type;//消息内心
    private String userJsonStr;//返回格式内容
    private String sfid;//fid值
    private String bodyString;//请求body
    private String sender_account;//发送人
    private String ref_sender_account;//机器回应
    private static final String FID="657d7abb7f681fffe4c06b4a";

    @RequestMapping("/testBn")
    @ResponseBody
    public String test(String result_type,String mid,String jqid,String type_text,String account,String fid){
        if (result_type==null){
            result_type="0";

        }

        if (result_type.equals("3")){
            userJsonStr = "{\n" +
                    //如果以人的身份发送，该人只能是自定义交互的发起人
                    "\"sender_botid\":\""+ jqid + "\",\n" +
                    "\"type\":\"attachment\",\n" +
                    "\"refer_msg_id\":\"" + mid + "\",\n" +
                    "\"message\": {\n" +
                    "\"url\": \"https://www.baidu.com/\",\n" +
                    "\"avatartype\": 0,\n" +
                    "\"head\": {\n" +
                    "\"text\": \"孙庆冲：/威胁情报查询10.10.10.10\"\n" +
                    "\n" +
                    "},\n" +
                    "\"body\": {\n" +
                    "\"title\": \"标题\",\n" +
                    "\"image\": \""+fid+"\",\n" +
                    "\"mix\": [\n" +
                    "{\n" +
                    "\"text\": \"第一张\",\n" +
                    "\"image\": \""+fid+"\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"text\": \"第二张\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"image\": \""+fid+"\"\n" +
                    "}\n" +
                    "]\n" +
                    "},\n" +
                    "\"fields\": [\n" +
                    "{\n" +
                    "\"name\": \"是否恶意\",\n" +
                    "\"text\": \"恶意\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"风险评估\",\n" +
                    "\"text\": \"高\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"情报标签\",\n" +
                    "\"text\": \"挖矿软件、挖矿事件\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"置信度\",\n" +
                    "\"text\": \"中\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"地理位置地理位置地理位置地理位置地理位置\",\n" +
                    "\"text\": \"荷兰被荷兰省阿姆斯特丹荷兰被荷兰省阿姆斯特丹荷兰被荷兰省阿姆斯特丹\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"注册机构\",\n" +
                    "\"text\": \"是否恶意\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"ASN\",\n" +
                    "\"text\": \"20473\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"注册机构\",\n" +
                    "\"text\": \"The Constant Company,LLC\"\n" +
                    "},\n" +
                    "{\n" +
                    "\"name\": \"网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型\",\n" +
                    "\"text\": \"--\"\n" +
                    "}\n" +
                    "]\n" +
                    "}" +
                    "}";
        }else if(result_type.equals("2")) {

            userJsonStr = "{\n" +
                    //如果以人的身份发送，该人只能是自定义交互的发起人
                    "\"sender_account\":\""+account+"\",\n" +
                    " \"sender_botid\": \"17557070391804134\","+
                    "\"type\":\"text\",\n" +
                    "\"refer_msg_id\":\"" + mid + "\",\n" +
                    "\"message\": {\n" +
                    "\"content\": \"织语帮忙处理文本引用功能\"\n" +
                    "}\n" +
                    "}";

        } else if (result_type.equals("1")){
            userJsonStr = "{\n" +
                    "\"result_code\":\"ok\",\n" +
                    "\"result_msg\":\"" + type_text + "，执行失败。\",\n" +
                    "\"result_type\":\"1\"" +
                    "}";

        }else {
            userJsonStr = "{\n" +
                    "\"result_code\":\"ok\",\n" +
                    "\"result_msg\":\"" + type_text + "，执行成功。\",\n" +
                    "\"result_type\":\"0\"" +
                    "}";

        }
        MyColor.println("返回给服务器：\n"+userJsonStr);
        return userJsonStr;
//        return userJsonStr;

    }
    @RequestMapping("/springMVC-demo4/testBn")
    @ResponseBody
    public String testBs(String tokenurl, String coid, String aid, String toAccount, String jqid,
                         String ast,
                         String posturl, String account, String gid, String timeout,
                         HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {

//        String queryString = request.getQueryString();
//        StringBuffer RequestURL = request.getRequestURL();
//        MyColor.println(RequestURL + "?" + queryString);
//        MyColor.println(username+","+password);
//        String tokenurl = request.getParameter("tokenurl");
//        String corpid = request.getParameter("corpid");
//        String appid = request.getParameter("appid");
//        String posturl = request.getParameter("posturl");
//        String account = request.getParameter("account");
//        String gid = request.getParameter("gid");
//        MyColor.println(request.getRequestURL());
//        MyColor.println("json内容" + body);
        request.setCharacterEncoding("utf-8");

        Enumeration e = request.getParameterNames();//获取所有参数名
        while (e.hasMoreElements()) {//通过Enumeration类中的hasMoreElements()判断是否还有参数名
            String parameterName = (String) e.nextElement(); //获取当前参数名
            //再通过request.getParameter("")的方法来获取对应参数名的值
            MyColor.println(parameterName + ": " + request.getParameter(parameterName));
        }


        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader bufferedReader = request.getReader();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();
        MyColor.println("body内容" + str);
        Gson gson = new Gson();
        DataToken token1 = gson.fromJson(str, DataToken.class);
        String msgSignature = token1.getMsgSignature();
        encrypt = token1.getEncrypt();
        String timeStamp = token1.getTimeStamp();
        String nonce = token1.getNonce();


        jieMiBody = this.encrypt;
        MyColor.println("解密的参数" + jieMiBody);
        GetPost getPost1 = new GetPost();
        try {
            post2 = getPost1.post2(jieMiBody, ast);
        } catch (Exception exception) {
            exception.printStackTrace();
            post2="";
        }
        MyColor.println("解密后内容=" + post2);
        s2 = "message_id\":\"";
        s3 = "event_type\":\"";
        message_id = post2.contains("message_id");
        message_fid = post2.contains("message_fid");


        event_type = "";
        if (post2 != null && post2 != "") {

            event_type = post2.substring(post2.indexOf(s3) + s3.length(), post2.indexOf("\",\"timestamp"));
        }

        if (post2 != null && post2 != "" && message_id) {
            Gson gson1 = new Gson();
            DataToken token2 = gson1.fromJson(post2, DataToken.class);
            mid= (String) token2.getEvent().get("message_id");
//            mid = post2.substring(post2.indexOf(s2) + s2.length(), post2.indexOf("\",\"message_text"));

        } else {
            mid = "";
        }

        switch (event_type) {
            case "main_tab_add_menu_click":
                type_text = "主界面“+”号菜单项";
                break;

            case "message_menu_click":
                fid = true;
                type_text = "消息菜单";
                break;
            case "chat_toolbar_click":
                type_text = "聊天工具栏";
                break;
            case "slash_command_click":
                type_text = "快捷指令";
                break;
            case "chat_attachment_bar_click":
                type_text = "聊天附件栏";
                break;
            case "mine_menu_click":
                type_text = "“我的”菜单";
                break;
            default:
                type_text = "没有操作类型";
                break;

        }
        MyColor.println("消息id=" + mid);
        if (timeout != null) {
            Thread.sleep(Integer.parseInt(timeout));
        }
        //判断客户输入参数
        String canShu = test.unicodeDecode(post2);
        MyColor.println("正确内容=" + canShu.replace("\\",""));
        //处理返回参数
        userJsonStr = "";
        //判断是机器还是应用
        if (jqid != null) {

            if (account == null) {
                sender_account = "";
            } else {
                sender_account = "\"sender_account\":\"" + account + "\",\n";
            }
            ref_sender_account = "sender_botid";
        }else {
            sender_account= "\"sender_account\":\"" + account + "\",\n";
            jqid=account;
            ref_sender_account = "sender_account";
        }

        if (canShu.contains("织语") /*&& mid != ""*/) {
            if (canShu.contains("交互")){
                userJsonStr = "{\n" +
                        //如果以人的身份发送，该人只能是自定义交互的发起人
                        "\""+ref_sender_account+"\":\"" + jqid + "\",\n" +
                        "\"type\":\"attachment\",\n" +
                        "\"refer_msg_id\":\"" + mid + "\",\n" +
                        "\"message\": {\n" +
                        "\"url\": \"https://www.baidu.com/\",\n" +
                        "\"avatartype\": 0,\n" +
                        "\"head\": {\n" +
                        "\"text\": \"孙庆冲：/威胁情报查询10.10.10.10\"\n" +
                        "\n" +
                        "},\n" +
                        "\"body\": {\n" +
                        "\"title\": \"标题\",\n" +
                        "\"image\": \""+FID+"\",\n" +
                        "\"mix\": [\n" +
                        "{\n" +
                        "\"text\": \"第一张\",\n" +
                        "\"image\": \""+FID+"\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"text\": \"第二张\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"image\": \""+FID+"\"\n" +
                        "}\n" +
                        "]\n" +
                        "},\n" +
                        "\"fields\": [\n" +
                        "{\n" +
                        "\"name\": \"是否恶意\",\n" +
                        "\"text\": \"恶意\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"风险评估\",\n" +
                        "\"text\": \"高\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"情报标签\",\n" +
                        "\"text\": \"挖矿软件、挖矿事件\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"置信度\",\n" +
                        "\"text\": \"中\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"地理位置地理位置地理位置地理位置地理位置\",\n" +
                        "\"text\": \"荷兰被荷兰省阿姆斯特丹荷兰被荷兰省阿姆斯特丹荷兰被荷兰省阿姆斯特丹\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"注册机构\",\n" +
                        "\"text\": \"是否恶意\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"ASN\",\n" +
                        "\"text\": \"20473\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"注册机构\",\n" +
                        "\"text\": \"The Constant Company,LLC\"\n" +
                        "},\n" +
                        "{\n" +
                        "\"name\": \"网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型网络类型\",\n" +
                        "\"text\": \"--\"\n" +
                        "}\n" +
                        "]\n" +
                        "}" +
                        "}";
            }else {

                userJsonStr = "{\n" +
                        //如果以人的身份发送，该人只能是自定义交互的发起人
                        "\"sender_account\":\"" + account + "\",\n" +
                        " \"sender_botid\": \""+jqid+"\","+
                        "\"type\":\"text\",\n" +
                        "\"refer_msg_id\":\"" + mid + "\",\n" +
                        "\"message\": {\n" +
                        "\"content\": \"织语帮忙处理文本引用功能\"\n" +
                        "}\n" +
                        "}";
            }
            MyColor.println("返回给服务器：\n"+userJsonStr);
            return userJsonStr;
        } else {
            // 先返回结果，然后异步执行
            ExecutorService executor = Executors.newCachedThreadPool();
            executor.execute(() -> {
                try {
                    Thread.sleep(1000 * 3);
                } catch (InterruptedException e3) {
                    e3.printStackTrace();
                }
//            以下是方法
                GetPost getPost = new GetPost();
                String token = null;
                try {
                    token = getPost.get(tokenurl, coid, aid);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                bodyString = "";
                if (gid != null) {
                    if (mid != "") {
                        if (fid) {

                            if (message_fid) {
                                bodyString = "{\n" +
                                        "\"to_group_id\":\"" + gid + "\",\n" +
                                        sender_account +
                                        "\"type\": \"text\",\n" +
                                        "\"message\": {\n" +
                                        "\"content\": \"" + type_text + "(文件)问题已收到，我们将尽快进行排查\"\n" +

                                        "}\n" +
                                        "}";
                            } else {

                                bodyString = "{\n" +
                                        "\"to_group_id\":\"" + gid + "\",\n" +
                                        sender_account +
                                        "\"type\": \"text\",\n" +
                                        "\"refer_msg_id\":\"" + mid + "\"," +
                                        "\"message\": {\n" +
                                        "\"content\": \"" + type_text + "（文字）问题已收到，我们将尽快进行排查\"\n" +

                                        "}\n" +
                                        "}";
                            }

                        } else {
                            bodyString = "{\n" +
                                    "\"to_group_id\":\"" + gid + "\",\n" +
                                    sender_account+
                                    "\"type\": \"text\",\n" +
                                    "\"refer_msg_id\":\"" + mid + "\"," +
                                    "\"message\": {\n" +
                                    "\"content\": \"" + type_text + "问题已收到，我们将尽快进行排查\"\n" +

                                    "}\n" +
                                    "}";
                        }


                    } else {
                        bodyString = "{\n" +
                                "\"to_group_id\":\"" + gid + "\",\n" +
                                sender_account +
                                "\"type\": \"text\",\n" +
                                "\"message\": {\n" +
                                "\"content\": \"" + type_text + "使用成功，我们将砥砺前行\"\n" +
                                "}\n" +
                                "}";

                    }


                }
                if (toAccount != null) {
                    bodyString = "{\n" +
                            "\"to_single_account\":\"" + toAccount + "\",\n" +
                            sender_account +
                            "\"type\": \"text\",\n" +
                            "\"message\": {\n" +
                            "\"content\": \"" + type_text + "问题已收到，我们将尽快进行排查\"\n" +
                            "}\n" +
                            "}";
                }
                createSignDemo createSignDemo = new createSignDemo();
                String qianMing = createSignDemo.getQianMing(bodyString, token, ast);
                // 这边执行具体的方法
                try {
                    getPost.post(bodyString, posturl, token,qianMing);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

            });
            executor.shutdown();

//        StringBuffer stringBuffer = new StringBuffer("");
//        BufferedReader bufferedReader = request.getReader();
//        String str = null ;
//        while((str=bufferedReader.readLine())!=null){
//            stringBuffer.append(str);
//        }
//        str = stringBuffer.toString() ;
//        MyColor.println(str);
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json;charset=utf-8");
            if (canShu.contains("失败")){
                userJsonStr = "{\n" +
                        "\"result_code\":\"ok\",\n" +
                        "\"result_msg\":\"" + type_text + "，执行成功。\",\n" +
                        "\"result_type\":\"1\"" +
                        "}";
            }else {
                userJsonStr = "{\n" +
                        "\"result_code\":\"ok\",\n" +
                        "\"result_msg\":\"" + type_text + "，执行成功。\",\n" +
                        "\"result_type\":\"0\"" +
                        "}";
            }



//        response.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");


            return userJsonStr;


        }

    }

    @GetMapping("/springMVC-demo4/testBn1")
    public String testBs1(String encrypt, String msgSignature, String timeStamp, String nonce,
                          HttpServletRequest request, HttpSession session, String ast) throws Exception {

        request.setCharacterEncoding("utf-8");
        String encrypt1 = request.getParameter("encrypt");

        String queryString = request.getQueryString();//所有请求参数的字符串
        System.out.println("+++++" + queryString);

        StringBuffer requestURL = request.getRequestURL();//请求地址（包含工程名）
//        MyColor.println(request.getRequestURI());//请求工程名
        Enumeration e = request.getParameterNames();//获取所有参数名
        while (e.hasMoreElements()) {//通过Enumeration类中的hasMoreElements()判断是否还有参数名
            String parameterName = (String) e.nextElement(); //获取当前参数名
            //再通过request.getParameter("")的方法来获取对应参数名的值
            MyColor.println(parameterName + ": " + request.getParameter(parameterName));
        }
        UrlMap urlMap = new UrlMap();
        Map<String, String> strUrlMap = urlMap.urlMap(queryString);
        encrypt=strUrlMap.get("encrypt");
//        String sss = "&encrypt=";
//        if (queryString != null) {
//
//            encrypt = queryString.substring(queryString.indexOf(sss) + sss.length());
//            MyColor.println("未解密前" + encrypt);
//        }
        MyColor.println("未解密前" + encrypt);
        encrypt = UriUtils.decode(encrypt, "utf-8");
        encrypt = UriUtils.decode(encrypt, "utf-8");

        String jieMiBody = encrypt;
        MyColor.println("解密的参数" + jieMiBody);
        GetPost getPost1 = new GetPost();
        post2 = getPost1.post2(jieMiBody, ast);
        MyColor.println("解密后内容=" + post2);
        session.setAttribute("mimi", post2);
        session.setAttribute("bsUrl", requestURL + "?" + queryString);
        return "success";
    }
}
